<template>
  <div class="permission" style="width:99%;margin-top:-25px;">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size">
        <el-form-item>
          <kt-button :label="$t('action.addmenu')" perms="AuthorityManagement:PermissionsList:add" type="primary" @click="handleAdd"/>
        </el-form-item>
      </el-form>
    </div>
    <!--表格树内容栏-->
    <div class="authTypeBox">
       <el-table :data="tableTreeDdata" stripe size="mini" height="730" style="width: 100%;" @findTreeData="findTreeData"
              v-loading="loading" element-loading-text="$t('action.loading')">
      <el-table-column
        prop="id" header-align="center" align="center" type="index"  label="序号">
      </el-table-column>
      <table-tree-column
        prop="menuName" header-align="center" treeKey="id" label="名称" >
      </table-tree-column>
      <el-table-column header-align="center" align="center" label="" width="0">
        <template slot-scope="scope">
          <i :class="scope.row.icon || ''"></i>
        </template>
      </el-table-column>
      <el-table-column prop="authType" header-align="center" align="center" label="类型"  width="80">
        <template slot-scope="scope">
          <!--<el-tag v-if="scope.row.parentId === 0" size="small">目录</el-tag>-->
          <el-tag v-if="scope.row.authType === 1" size="small" type="success">菜单</el-tag>
          <el-tag v-else-if="scope.row.authType === 2" size="small" type="info">按钮</el-tag>
        </template>
      </el-table-column>
      <!--<el-table-column-->
        <!--prop="orderNumber"  header-align="center" align="center" label="排序">-->
      <!--</el-table-column>-->
      <el-table-column
        prop="menuUrl" header-align="center" align="center"
        :show-overflow-tooltip="true" label="菜单URL" width='200'>
      </el-table-column>
      <el-table-column
        prop="commonButton" header-align="center" align="center"
        width="100"
        :show-overflow-tooltip="true" label="授权标识">
      </el-table-column>
      <el-table-column
        fixed="right" header-align="center" align="center"  :label="$t('action.operation')"  width="400">
        <template slot-scope="scope">
          <kt-button :label="$t('action.top')"  perms="AuthorityManagement:PermissionsList:top"  v-if="scope.row.isTop&&scope.row.authType==1" @click="handleTop(scope,scope.row)"/>
          <kt-button :label="$t('action.down')"  perms="AuthorityManagement:PermissionsList:down" v-if="scope.row.isDown&&scope.row.authType==1" @click="handleDown(scope.$index,scope.row)"/>
          <kt-button :label="$t('action.edit')" perms="AuthorityManagement:PermissionsList:edit" type="primary" commonButton="sys:menu:edit" @click="handleEdit(scope.row)"/>
          <kt-button  class="delete" :label="$t('action.delete')" perms="AuthorityManagement:PermissionsList:delete" commonButton="sys:menu:delete" type="danger" @click="handleDelete(scope.row)"/>
        </template>
      </el-table-column>
    </el-table>
    </div> 
   
    <!-- 新增修改界面 -->
    <el-dialog :title="!dataForm.id ? '新增' : '修改'" width="40%" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="submitForm()"
                 label-position="center" :size="size" >
        <el-form-item label="菜单类型" prop="authType" v-if="!dataForm.id"  style="text-align: left">
          <el-radio-group v-model="dataForm.authType"   >
            <el-radio v-for="(authType, index) in menuTypeList" :label="index" :key="index" >{{ authType }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item  :label="menuTypeList[dataForm.authType] + '名称'" prop="menuName">
            <el-input v-model="dataForm.menuName" :placeholder="menuTypeList[dataForm.authType] + '名称'"></el-input>
        </el-form-item>
        <el-form-item label="上级菜单" prop="parentId" v-if="!dataForm.id">
          <popup-tree-input
            :data="popupTreeData" :props="popupTreeProps" :prop="dataForm.parentName==null?'顶级菜单':dataForm.parentName"
            :nodeKey="''+dataForm.parentId" :currentChangeHandle="handleTreeSelectChange">
          </popup-tree-input>
        </el-form-item>
        <el-form-item  v-if="dataForm.authType === 1" label="菜单路由" prop="menuUrl">
          <el-input v-model="dataForm.menuUrl" placeholder="菜单路由"></el-input>
        </el-form-item>
        <el-form-item v-if="dataForm.authType === 2" label="授权标识" prop="commonButton">
          <el-input v-model="dataForm.commonButton" placeholder="规则：一级路由:二级路由:按钮英文 如: AuthorityManagement:PermissionsList:add   添加（add）"></el-input>
        </el-form-item>
        <!--<el-form-item v-if="dataForm.authType !== 2" label="排序编号" prop="orderNum">-->
          <!--<el-input-number v-model="dataForm.orderNumber" controls-position="right" :min="0" label="排序编号"></el-input-number>-->
        <!--</el-form-item>-->
        <!--<el-form-item v-if="dataForm.authType !== 2" label="菜单图标" prop="icon">-->
          <!--<el-row>-->
            <!--<el-col :span="22">-->
              <!--&lt;!&ndash; <el-popover-->
                <!--ref="iconListPopover"-->
                <!--placement="bottom-start"-->
                <!--trigger="click"-->
                <!--popper-class="mod-menu__icon-popover">-->
                <!--<div class="mod-menu__icon-list">-->
                  <!--<el-button-->
                    <!--v-for="(item, index) in dataForm.iconList"-->
                    <!--:key="index"-->
                    <!--@click="iconActiveHandle(item)"-->
                    <!--:class="{ 'is-active': item === dataForm.icon }">-->
                    <!--<icon-svg :name="item"></icon-svg>-->
                  <!--</el-button>-->
                <!--</div>-->
              <!--</el-popover> &ndash;&gt;-->
              <!--<el-input v-model="dataForm.icon" v-popover:iconListPopover :readonly="false" placeholder="菜单图标名称（如：fa fa-home fa-lg）" class="icon-list__input"></el-input>-->
            <!--</el-col>-->
            <!--<el-col :span="2" class="icon-list__tips">-->
              <!--<fa-icon-tooltip />-->
            <!--</el-col>-->
          <!--</el-row>-->
        <!--</el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size"  @click="dialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button :size="size"  v-if="!dataForm.id" type="primary" @click="submitForm()">{{$t('action.comfirm')}}</el-button>
        <el-button :size="size"  v-if="dataForm.id" type="primary" @click="submitForm1()">{{$t('action.comfirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import KtButton from "@/views/Core/KtButton"
  import TableTreeColumn from '@/views/Core/TableTreeColumn'
  import PopupTreeInput from "@/components/PopupTreeInput"
  import FaIconTooltip from "@/components/FaIconTooltip"
  import axios from 'axios';
  export default {
    components:{
      PopupTreeInput,
      KtButton,
      TableTreeColumn,
      FaIconTooltip
    },
    data() {
      return {
        size: 'small',
        loading: false,
        filters: {
          menuName: ''
        },
        tableTreeDdata: [],
        dialogVisible: false,
        menuTypeList: ['目录','菜单', '按钮'],
        dataForm: {
          id: 0,
          authType: 1,
          menuName: '',
          parentId: 0,
          parentName: '',
          menuUrl: '',
          commonButton: '',
          orderNumber: 0,
          icon: '',
          iconList: [],
          menuLevel:""
        },
        dataRule: {
          menuName: [
            { required: true, message: '菜单名称不能为空', trigger: 'blur' }
          ],
          parentName: [
            { required: true, message: '上级菜单不能为空', trigger: 'change' }
          ]
        },
        popupTreeData: [],
        levelTree:[], //平级树集合
        popupTreeProps: {
          label: 'menuName',
          children: 'children'
        }
      }
    },
    methods: {
      //向上
      handleTop:function (index,row) {
        if(row.parentId == 0){
          this.$api.menu.findLevelTree({parentId:0}).then( res=>{
            this.levelTree=res.authorityList
            var i
            for(i=0;i<this.levelTree.length;i++){
              if(row.id == this.levelTree[i].id){
                this.$api.menu.changeMenu({authId1:this.levelTree[i].id,authId2:this.levelTree[i-1].id}).then(res => {
                  if(res.result == 1){
                    this.$message({ message: res.msg, type: 'success' })
                  }else{
                    this.$message({ message: res.msg, type: 'error' })
                  }
                  this.findTreeData()
                })
              }
            }
          })
        }else{
          this.$api.menu.findLevelTree({parentId:row.parentId}).then( res=>{
            this.levelTree=res.authorityList
            var i
            for(i=0;i<this.levelTree.length;i++){
              if(row.id == this.levelTree[i].id){
                this.$api.menu.changeMenu({authId1:this.levelTree[i].id,authId2:this.levelTree[i-1].id}).then(res => {
                  if(res.result == 1){
                    this.$message({ message: res.msg, type: 'success' })
                  }
                  this.findTreeData()
                })
              }
            }
          })
        }
      },
      //向下
      handleDown:function (index,row) {
        if(row.parentId == 0){
          this.$api.menu.findLevelTree({parentId:0}).then( res=>{
            this.levelTree=res.authorityList
            var i
            for(i=0;i<this.levelTree.length;i++){
              if(row.id == this.levelTree[i].id){
                this.$api.menu.changeMenu({authId1:this.levelTree[i].id,authId2:this.levelTree[i+1].id}).then(res => {
                  if(res.result == 1){
                    this.$message({ message: res.msg, type: 'success' })
                  }
                  this.findTreeData()
                })
              }
            }
          })
        }else{
          this.$api.menu.findLevelTree({parentId:row.parentId}).then( res=>{
            this.levelTree=res.authorityList
            var i
            for(i=0;i<this.levelTree.length;i++){
              if(row.id == this.levelTree[i].id){
                this.$api.menu.changeMenu({authId1:this.levelTree[i].id,authId2:this.levelTree[i+1].id}).then(res => {
                  if(res.result == 1){
                    this.$message({ message: res.msg, type: 'success' })
                  }
                  this.findTreeData()
                })
              }
            }
          })
        }
      },
      // 获取数据
      findTreeData: function () {
        this.loading = true
        this.$api.menu.findMenuTree().then((res) => {
          this.tableTreeDdata = res.authorityList
          this.appendIs(this.tableTreeDdata)
          this.tableTreeDdata[0].isTop=false
          this.tableTreeDdata[this.tableTreeDdata.length-1].isDown=false
          var arrTree=this.tableTreeDdata
          for(let i=0; i<arrTree.length;i++){
            if(arrTree[i].children){
              arrTree[i].children[0].isTop=false
              arrTree[i].children[arrTree[i].children.length-1].isDown=false
            }
          }
          this.tableTreeDdata=arrTree
          this.popupTreeData = this.getParentMenuTree(res.authorityList)
          this.loading = false
        })
      },
      //递归添加字段
      appendIs:function (obj) {
        obj.forEach(item =>{
          item.isTop=true
          item.isDown=true
          if(item.children ){
            this.appendIs(item.children)
          }
        })

      },
      // 获取上级菜单树
      getParentMenuTree: function (tableTreeDdata) {
        let parent = {
          parentId: 0,
          menuName: '顶级菜单',
          children: tableTreeDdata
        }
        return [parent]
      },
      // 显示新增界面
      handleAdd: function () {
        this.dialogVisible = true
        this.dataForm = {
          id: "",
          authType: 1,
          typeList: ["目录",'菜单', '按钮'],
          menuName: '',
          parentId: 0,
          parentName: '',
          menuUrl: '',
          commonButton: '',
          orderNumber: 0,
          icon: '',
          iconList: [],
          menuLevel:""
        }
      },
      // 显示编辑界面
      handleEdit: function (row) {
        this.dialogVisible = true
        Object.assign(this.dataForm, row);
      },
      // 删除
      handleDelete (row) {
          this.$confirm('确认删除选中记录吗？', '提示', {
            type: 'warning'
          }).then(() => {
            let params = this.getDeleteIds([], row);
            this.$api.menu.batchDelete({"authId":params[0].id}).then( res => {
              this.findTreeData()
              this.$message({message: res.msg, type: 'success'})
            })
          })
      },
      // 获取删除的包含子菜单的id列表
      getDeleteIds (ids, row) {
        ids.push({id:row.id})
        if(row.children != null) {
          // for(let i=0, len=row.children.length; i<len; i++) {
          //   this.getDeleteIds(ids, row.children[i])
          // }
          this.$alert("当前菜单下有子菜单，不可删除", "提示", { 
            confirmButtonText: "确定"
          });
          return ids=null
        }
        else {
          return ids
        }
      },
      // 菜单树选中
      handleTreeSelectChange (data, node) {
        this.dataForm.parentId = data.id
        this.dataForm.parentName = data.menuName
        this.dataForm.menuLevel = node.level
      },
      // 图标选中
      iconActiveHandle (iconName) {
        this.dataForm.icon = iconName
      },
      // 保存表单提交
      submitForm () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.editLoading = true
              let params = Object.assign({}, this.dataForm)
              this.$api.menu.save(params).then((res) => {
                this.editLoading = false
                if(res.result == 1) {
                  this.$message({ message: res.msg, type: 'success' })
                  this.$refs['dataForm'].resetFields()
                  this.dialogVisible = false
                } else {
                  this.$message({message: res.msg, type: 'error'})
                }
                this.findTreeData()
              })
            })
          }
        })
      },
      // 编辑表单提交
      submitForm1 () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.editLoading = true
              let params = Object.assign({}, this.dataForm)
              this.$api.menu.handleEdit(params).then((res) => {
                this.editLoading = false
                if(res.result == 1) {
                  this.$message({ message: res.msg, type: 'success' })
                  this.$refs['dataForm'].resetFields()
                  this.dialogVisible = false
                } else {
                  this.$message({message: res.msg, type: 'error'})
                }
                this.findTreeData()
              })
            })
          }
        })
      }
    },
    mounted() {
      this.findTreeData()
    }
  }
</script>

<style>
.permission .el-radio-group .el-radio:nth-child(1){
  display: none;
}
.permission .el-form-item__label{
  min-width: 80px;
}
.permission .el-dialog__wrapper .el-form-item__content{
    margin-left: 100px;
}
</style>
<style lang="scss">
.authTypeBox{
.el-table__row td > .cell {
  text-align: left !important;
}
}

</style>
